import { postDecisionFlowGetProcessDetail } from '@/api';
import { TApprovalConclusion } from '@/hooks/useCurrentTaskInfo';
import { useUser } from '@/hooks/useUser';
import { useAppStore } from '@/store/app';
import { TApprovalHistoryData } from '.';

// 当前用户是否存在于审批中的处理人中
export const isApprovalHandler = async (processInstanceId: string) => {
  const appStore = useAppStore();
  let isHandler = null as TNullable<boolean>;
  const data = await postDecisionFlowGetProcessDetail({ flowId: processInstanceId });
  if (!data?.taskActivities?.length) return isHandler;
  const { taskActivities, historicProcessInstance } = data;
  // 不是审批中状态直接返回空
  if (historicProcessInstance?.approvalConclusion !== 'PROCESSING') return isHandler;

  taskActivities?.forEach((item) => {
    item.userTasks?.forEach((task) => {
      const { approvalStatus, assigneeUsers } = task;

      // 审批中的任务
      if (!approvalStatus && assigneeUsers) {
        assigneeUsers.forEach((user) => {
          if (!isHandler) {
            isHandler = appStore.mcisaas.userId === user.userId;
          }
        });
      }
    });
  });
  return isHandler;
};
export const useApprovalUserType = (data?: TApprovalHistoryData | null) => {
  const { userId } = useUser().value;
  const isSubmitUser = ref(false); // 提交人
  const isApprovalUser = ref(false); // 当前审批流 所有的审批人
  const isCurApprovalUser = ref(false); // 当前 正在审批的人
  const isApprovalCompleted = ref(false); // 审批是否已完成

  const initUser = (progressData?: TApprovalHistoryData) => {
    if (!progressData) return;
    const { taskActivities, startActivity } = progressData;

    // 提交人
    if (startActivity?.stater?.userId === userId) {
      isSubmitUser.value = true;
    }
    const approveUserIds: number[] = [];
    const approveCurUserIds: number[] = [];
    taskActivities?.forEach((item) => {
      item.userTasks?.forEach((task) => {
        // 审批中的任务
        task.assigneeUsers?.forEach((user) => {
          approveUserIds.push(user.userId!);
          if (!task.approvalStatus) {
            approveCurUserIds.push(user.userId!);
          }
        });
      });
    });
    isApprovalUser.value = approveUserIds.some((id) => id === userId);
    isCurApprovalUser.value = approveCurUserIds.some((id) => id === userId);
  };

  data && initUser(data);

  return {
    isSubmitUser,
    isApprovalUser,
    isCurApprovalUser,
    isApprovalCompleted,
    initUser
  };
};

export const useMode = () => {
  const detailMode = ref<'view' | 'edit'>('edit');
  const approvalMode = ref<'view' | 'edit'>('edit'); // 审批的操作权限
  const { isSubmitUser, isApprovalUser, isCurApprovalUser, initUser } = useApprovalUserType();

  const onProcessing = () => {
    // 审批中： 审批人有审批操作
    approvalMode.value = isCurApprovalUser.value ? 'edit' : 'view';
    // 审批中：内容只读
    detailMode.value = 'view';
  };

  const onPassed = () => {
    // 审批完成：全部只读
    approvalMode.value = 'view';
    detailMode.value = 'view';
  };

  const onRejected = () => {
    // 审批驳回：全部只读
    approvalMode.value = 'view';
    // 审批驳回：提交人可编辑
    detailMode.value = isSubmitUser.value ? 'edit' : 'view';
  };

  const onUnApproval = () => {
    // 未开始审批：  审批组件不可见
    approvalMode.value = 'view';
    // 未开始审批： 提交人可编辑
    detailMode.value = isSubmitUser.value ? 'edit' : 'view';
  };

  const initMode = (approvalConclusion: TApprovalConclusion, progressData?: TApprovalHistoryData) => {
    initUser(progressData);
    switch (approvalConclusion) {
      case 'PROCESSING':
        onProcessing();
        break;
      case 'PASSED':
        onPassed();
        break;
      case 'REJECTED':
        onRejected();
        break;
      default:
        onUnApproval();
    }
  };
  return {
    detailMode,
    approvalMode,
    initMode,
    isSubmitUser,
    isApprovalUser
  };
};
